package com.java.basis.thread;

import java.util.concurrent.*;

/**
 * @author wangning
 * @date 2023/5/16 14:46
 * java
 * 多线程中，第三种创建线程的方式
 * 例如分片计算结果，最后想加
 */
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread02 myThread02 = new MyThread02();
        FutureTask<Integer> futureTask = new FutureTask<>(myThread02);
        FutureTask<Integer> futureTask2 = new FutureTask<>(myThread02);
        new Thread(futureTask, "AAA").start();//多个线程计算，只计算一次，如果非要计算多次，就要启动多个futureTask
        new Thread(futureTask, "BBB").start();
        new Thread(futureTask2, "CCC").start();

        int result = 100;
//        while (!futureTask.isDone()) {
//
//        }
        Integer res = futureTask.get();//建议放在最后，要求获得callable线程的计算结果，如果没有计算完成就要去强求，会导致阻塞，直到计算完成
        System.out.println(res + result);

    }
}

class MyThread01 implements Runnable {

    @Override
    public void run() {

    }
}

/**
 * 有返回值，用来返回线程出问题的原因
 */
class MyThread02 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\tcome in callable");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1024;
    }
}
